package com.gykfbxxh.imovie.manager;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Process;
import android.text.TextUtils;

import com.app.utils.util.AppTools;
import com.app.utils.util.StringUtils;
import com.baidu.mobstat.StatService;
import com.google.gson.Gson;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.BuildConfig;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.config.TypeConstant;
import com.gykfbxxh.imovie.receiver.UmengPushMessageReceiver;
import com.gykfbxxh.imovie.utils.DialogUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.IUmengUnregisterCallback;
import com.umeng.message.PushAgent;

import java.util.List;

/**
 * Created by Guo on 2016/8/8.
 * <p>
 * 推送的管理类
 */
public class IPushManager implements DialogUtils.OnDialogBtnClickListener {

    private static IPushManager iPushManager;
    private FilmEntity newsEntity;//当前推送的实体类信息
    private Activity activity;
    private String pushType;


    private IPushManager() {
    }


    public static IPushManager getInstance() {
        if (iPushManager == null) {
            iPushManager = new IPushManager();
        }
        return iPushManager;
    }


    /**
     * 初始化友盟推送
     */
    public void initUmengPush() {

        //开启友盟的自定义消息推送
        UmengPushMessageReceiver umengPushMessageReceiver = new UmengPushMessageReceiver();

        final PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
        final String versionName = AppTools.getVersionName();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    mPushAgent.getTagManager().add(versionName);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

        //开启/关闭友盟的调试模式
        mPushAgent.setDebugMode(BuildConfig.LOG_DEBUG);

        mPushAgent.setMessageHandler(umengPushMessageReceiver);
        mPushAgent.enable(iUmengRegisterCallback);

    }


    /**
     * 如果是小米手机,就只注册小米的推送
     * 如果是非小米手机,注友盟
     */
    public void initDoublePushByBuildMode() {
        if (AppConfigManager.getInstance().readConfig(ConfigKey.option_isPull, true)) {
            initUmengPush();
        }
    }


    /**
     * 停止推送
     * 根据机型停止对应的推送
     */
    public void endPush() {
            //关闭友盟推送
        PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
        mPushAgent.disable(iUmengUnregisterCallback);

        AppConfigManager.getInstance().writeConfig(ConfigKey.push_dialog_show_time, 0L);

    }


    /**
     * 开启推送
     * 根据机型开启对应的push
     */
    public void startPush() {
        PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
        mPushAgent.enable(iUmengRegisterCallback);
        AppConfigManager.getInstance().writeConfig(ConfigKey.option_isPull, true);


    }

    /**
     * 友盟注销的回调监听
     */
    public IUmengUnregisterCallback iUmengUnregisterCallback = new IUmengUnregisterCallback() {
        @Override
        public void onUnregistered(String s) {
            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
            boolean enabled = mPushAgent.isEnabled();
        }
    };


    /**
     * 友盟注册的回调
     */
    public IUmengRegisterCallback iUmengRegisterCallback = new IUmengRegisterCallback() {
        @Override
        public void onRegistered(String s) {
            AppConfigManager.getInstance().writeConfig(AppConfigTools.UMENG_TOKEN, s);
            PushAgent mPushAgent = PushAgent.getInstance(AppApplication.getInstance());
            boolean enabled = mPushAgent.isEnabled();

        }
    };


    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) AppApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = AppApplication.getInstance().getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 通知栏弹窗
     */
    public void showNotification(Context context, FilmEntity newsEntity, String pushType) {
//        if (newsEntity == null) return;
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
//        String articleType = newsEntity.getArticleType();
//        String articleId = newsEntity.getFId();
//        String articleTitle = newsEntity.getFName();
//        String articleSummary = newsEntity.getArticleSummary();
//        builder.setContentTitle(articleTitle);
//        builder.setContentText(articleSummary);
//
//        //大于等于23系统,则使用黑白的icon,否则,使用彩色的icon,不过现在图标还没有设计好.所以先用彩色的
////        LogUtils.e("gzq", "sdkInt = "+sdkInt);
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            builder.setSmallIcon(R.mipmap.icon);//只能是纯色
//        } else {
//            builder.setSmallIcon(R.mipmap.icon);
//        }
//
//        //大图标
//        builder.setLargeIcon(BitmapFactory.decodeResource(AppApplication.getInstance().getResources(),R.mipmap.icon));
//
//        builder.setDefaults(Notification.DEFAULT_ALL);
////        builder.setColor(Color.parseColor("#000000"));//设置icon 的背景颜色
//        builder.setAutoCancel(true);
//
//
//        //设置intent.如果有url,则直接跳转url
//        Intent intent = new Intent();
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra(BaseActivity.PARAMETER1, articleId);
//        intent.putExtra(BaseActivity.PARAMETER2, articleType);
//        intent.putExtra(TypeConstant.PUSH_TYPE, pushType);
//        if (!TextUtils.isEmpty(newsEntity.getJumpUrl())) {
//            intent.putExtra("url", newsEntity.getJumpUrl());
//        }
//        intent.putExtra(DispatchActivity.PUSH_OR_WAKEUP,true);
//        intent.setClass(context, DispatchActivity.class);
//
//        int id = (int) (System.currentTimeMillis() / 1000);
//
//        PendingIntent pendingIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        builder.setContentIntent(pendingIntent);
//
//
//        long articleIdLong = StringUtils.toLong(articleId, 0);
//        int articleIdInt = Long.valueOf(articleIdLong).intValue();
//
//        Notification notification = builder.build();
//
//        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//        nm.notify(articleIdInt, notification);


    }

    /**
     * 设置推送渠道号
     *
     * @param pushChannel
     */
    public void setPushChannel(String pushChannel) {
        if (!TextUtils.isEmpty(pushChannel)) {
            PushAgent.getInstance(AppApplication.getInstance()).setMessageChannel(pushChannel);
        }
    }


    /**
     * 判断 当前应用是否在前台运行
     *
     * @param context
     * @return
     */
    public boolean isAppIsInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String activeProcess : processInfo.pkgList) {
                        if (activeProcess.equals(context.getPackageName())) {
                            isInBackground = false;
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }

        return isInBackground;
    }

    /**
     * 要闻推送的弹窗
     *
     * @param activity
     * @param newsEntity 此参数为空的时候，读取本地数据，否则，立即弹出dialog
     * @param pushType   推送类型
     */
    public void showFoucsDialog(Activity activity, FilmEntity newsEntity, String pushType) {
        if (!AppConfigTools.isShowPushDialog) {
            return;
        }
        this.activity = activity;
        this.pushType = pushType;
        AppConfigTools.isShowPushDialog = false;
        if (newsEntity != null) {//如果有文章id，直接弹出dialog
            this.newsEntity = newsEntity;
            showPushDialog(activity);
        } else {//否则，去除本地数据，比较过后再弹
            String pushData = AppConfigManager.getInstance().readConfig(ConfigKey.push_foucusnews, "");
            if (!TextUtils.isEmpty(pushData)) {
                String[] pushStr = pushData.split("\\}_");
                if (pushStr.length >= 3) {
                    String pushContent = pushStr[0];
                    String pushTime = pushStr[1];
                    this.pushType = pushStr[2];
                    Long pushMills = Long.valueOf(pushTime);
                    long l = System.currentTimeMillis();
                    String pushExpireTimeStr = AppConfigManager.getInstance().readConfig(ConfigKey.push_expireTime, "7200");
                    long pushExpireTimeLong = StringUtils.toLong(pushExpireTimeStr, 7200L);

                    if ((l - pushMills) > (pushExpireTimeLong * 1000)) {//当前时间超过两小时，重置
                        AppConfigManager.getInstance().writeConfig(ConfigKey.push_foucusnews, "");
                    } else {
                        //解析content
                        Gson gson = new Gson();
                        try {
                            this.newsEntity = gson.fromJson(pushContent, FilmEntity.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            gson = null;
                        }
                        showPushDialog(activity);
                    }
                }
            }
        }
    }


    private void showPushDialog(Activity activity) {
//        HashMap<String, String> style = new HashMap<>();
//        style.put("title", activity.getString(R.string.push_dialog_title));
//        style.put("desc", this.newsEntity.getArticleTitle());
//        style.put("btnPosi", activity.getString(R.string.push_go));
//        style.put("btnNega", activity.getString(R.string.push_ignore));
//
//        DialogUtils.getInstance().setOnDialogBtnClick(this);
//        DialogUtils.getInstance().showCustomDialog(activity, style);
//
//        AppConfigManager.getInstance().writeConfig(ConfigKey.push_foucusnews, "");
    }


    @Override
    public void onPositiveClick() {
        DialogUtils.getInstance().dismissCustomDialog();
        StatService.onEvent(AppApplication.getInstance(), "028", "要闻推送点击", 1);// 统计的点击的次数

        TypeConstant.openTypeDetail(newsEntity, activity, "");//跳转新闻详情

    }

    @Override
    public void onNegativeClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }
}
